<?php

App::uses('AdminAppController', 'Admin.Controller');
App::uses('AppController', 'Controller');

class AdminUsersController extends AdminAppController {

    var $name = 'AdminUsers';
    var $helpers = array('Form');

    function index() {
        $this->loadModel('Admin');
        $this->paginate = array(
            //'conditions' => array('Admin.id !=' => '6'),
            'limit' => 25,
            'order' => array('Admin.id' => 'desc')
        );

        // we are using the 'Admin' model
        $users = $this->paginate('Admin');

        // pass the value to our view.ctp
        $this->set('users', $users);
    }

    function edit($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }
        $this->loadModel('Admin');
        $post = $this->Admin->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }

        if ($this->request->is(array('post', 'put'))) {
            $this->Admin->id = $id;

            if ($this->request->data['password']) {
                $this->request->data['password'] = md5($this->request->data['password']);
            } else {
                unset($this->request->data['password']);
            }

            if ($this->Admin->save($this->request->data)) {
                $this->Session->setFlash('User has been updated.!', 'default', array(), 'good');
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash('Unable to update user.!', 'default', array(), 'bad');
        }

        if (!$this->request->data) {
            $this->request->data = $post;
        }
    }
    
    function add() {        
        $this->loadModel('Admin');       

        if ($this->request->is(array('post', 'put'))) {
            if ($this->Admin->save($this->request->data)) {
                $this->Session->setFlash('User has been created.!', 'default', array(), 'good');
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash('Unable to create user.!', 'default', array(), 'bad');
        }
    }

    function delete($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }

        $this->loadModel('Admin');

        $current_user = $this->Session->read('User');
        if ($current_user['Admin']['id'] != $id) {
            if ($this->Admin->delete($id)) {
                $this->Session->setFlash('Delete success!', 'default', array(), 'good');
            } else {
                $this->Session->setFlash('Delete unsuccess!', 'default', array(), 'bad');
            }
        } else {
            $this->Session->setFlash('You can not delete yourself', 'default', array(), 'bad');
        }
        $this->Redirect(array('action' => 'index'));
    }

}
